package com.zxh.blog.util.excelDemo;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @Author:wb-zxh410423
 * @Description: excel的所有列的配置
 * @Date: Created in 13:43 2018/12/11
 */
public class ExcelColumnsConfigMap {

	/**
	 * 所有列的配置，列头名为key
	 */
	private Map<String,ExcelColumnConfigModel> configModelMap = new HashMap<>();

	public ExcelColumnsConfigMap(Map<String,ExcelColumnConfigModel> configModelMap){
		this.configModelMap = configModelMap;
	}

	/**
	 * 某列是否可为空
	 * @param headerName
	 * @return
	 */
	public boolean canEmpty(String headerName){
		ExcelColumnConfigModel columnConfigModel = configModelMap.get(headerName);
		return columnConfigModel == null || !columnConfigModel.canEmpty();
	}

	/**
	 * 获取某列的配置
	 * @param headerName
	 * @return
	 */
	public Optional<ExcelColumnConfigModel> getConfig(String headerName) {
		ExcelColumnConfigModel field = configModelMap.get(headerName);
		return Optional.ofNullable(field);
	}

	/**
	 * 获取表头信息
	 * @return
	 */
	public List<String> getHeaderName(){
		Set<Map.Entry<String, ExcelColumnConfigModel>> entries = configModelMap.entrySet();
		Iterator<Map.Entry<String, ExcelColumnConfigModel>> iterator = entries.iterator();
		ArrayList<String> list = new ArrayList<>();
		for (int i = 0; i < configModelMap.size(); i++) {
			list.add("");
		}
		int index = 0;
		while (iterator.hasNext()){
			ExcelColumnConfigModel excelColumnConfigModel = iterator.next().getValue();
			if(excelColumnConfigModel.getColIndex() >= configModelMap.size()) {
			}
			if(-1 != excelColumnConfigModel.getColIndex()){
				list.set(excelColumnConfigModel.getColIndex(),excelColumnConfigModel.getHeaderName());
			}else{
				list.set(index,excelColumnConfigModel.getHeaderName());
				index++;
			}
		}
		return list;
	}

	/**
	 * 解析注解配置
	 * @param clz
	 * @return
	 */
	public static ExcelColumnsConfigMap parse(Class clz){
		HashMap<String, ExcelColumnConfigModel> map = new HashMap<>();
		for(Field field : ReflectUtils.getAllFields(clz)){
			ExcelHeaderConfig annotation = field.getAnnotation(ExcelHeaderConfig.class);
			if(annotation != null && StringUtils.isNoneBlank(annotation.headerName())){
				ExcelColumnConfigModel excelColumnConfigModel = new ExcelColumnConfigModel(annotation.name(), annotation.headerName(), annotation.canEmpty(), annotation.colIndex());
				map.put(annotation.headerName(),excelColumnConfigModel);
			}
		}
		return new ExcelColumnsConfigMap(map);
	}

}
